package cn.schoolwow.quickapi.module.common.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class GetGenericTypeRecycleClassNameFlow implements BusinessFlow {
    private Logger logger = LoggerFactory.getLogger(GetGenericTypeRecycleClassNameFlow.class);

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Type rootType = (Type) flowContext.checkData("rootType");

        List<Class> classList = new ArrayList<>();
        if (rootType instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) rootType;
            Type genericType = pType.getActualTypeArguments()[0];
            String typeName = genericType.getTypeName();
            while(typeName.contains("<")){
                try {
                    classList.add(ClassLoader.getSystemClassLoader().loadClass(typeName.substring(0,typeName.indexOf("<"))));
                } catch (ClassNotFoundException e) {
                    logger.warn("[找不到参数或返回值泛型类]{}",e.getMessage());
                }
                typeName = typeName.substring(typeName.indexOf("<")+1,typeName.length()-1);
            }
            try {
                classList.add(ClassLoader.getSystemClassLoader().loadClass(typeName));
            } catch (ClassNotFoundException e) {
                logger.warn("[找不到参数或返回值泛型类]{}",e.getMessage());
            }
        }
        for(Class rootClazz:classList){
            flowContext.startFlow(new GetRecycleClassNameFlow())
                    .putCurrentCompositeFlowData("rootClazz", rootClazz)
                    .execute();
        }
    }

    @Override
    public String name() {
        return "获取泛型关联实体类信息";
    }
}
